//
//  Strings.swift
//  JXBaseTools
//
//  Created by godox on 2021/11/30.
//

import UIKit

extension String: JXCompatible {}

extension JX where Base == String {
    
    public var isEmpty: Bool { base == "" }
    
    public var toInt: Int {
        if let num = NumberFormatter().number(from: base) {
            return num.intValue
        }
        return 0
    }

    public var toDouble: Double {
        if let num = NumberFormatter().number(from: base) {
            return num.doubleValue
        }
        return 0.0
    }

    public var toFloat: Float {
        if let num = NumberFormatter().number(from: base) {
            return num.floatValue
        }
        return 0.0
    }
    
    public var toDict: [String: Any]? {
        guard let data = base.data(using: .utf8),
              let dict = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        else {
            return nil
        }
        return dict
    }
    
    /// 十六进制-->十进制
    public var toDecimal: Int {
        
        let str = base.uppercased()
        var sum = 0
        for i in str.utf8 {
            // 0-9 从48开始
            sum = sum * 16 + Int(i) - 48
            // A-Z 从65开始，但有初始值10，所以应该是减去55
            if i >= 65 {
                sum -= 7
            }
        }
        return sum
    }
    
    /// URL编码
    public var urlEncoded: String {
        let characterSet = CharacterSet(charactersIn: ":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`")
        return base.addingPercentEncoding(withAllowedCharacters: characterSet)!
    }
    /// URL解码
    public var urlDecode: String? {
        return base.removingPercentEncoding
    }
    
    /// URL中有中文的转码
    public var transcoding: String {
        return base.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? ""
    }
    
    
    /// base64编码
    public var base64: String {
        let plainData = (base as NSString).data(using: String.Encoding.utf8.rawValue)
        let base64String = plainData!.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
        return base64String
    }
    /// Base64解码
    public var base64Decode: String? {
        
        if let data = Data(base64Encoded: base) {
            return String(data: data, encoding: .utf8)
        }
        return nil
    }
    
    ///是否是邮箱
    public var isEmail: Bool {
        return base.range(of: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}", options: .regularExpression, range: nil, locale: nil) != nil }
    /// 是否是URL
    public var isValidUrl: Bool {
        return URL(string: base) != nil
    }
    
    /// 是否是手机号
    public var isMobile: Bool {
        guard !base.isEmpty else{
            return false
        }
        
        //手机号以13-19[0-9]开头，八个 \d 数字字符
        let phoneRegix = "^((1[3-9][0-9]))\\d{8}$"
        let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegix)
        return phoneTest.evaluate(with: base)
    }
    /// 是否是字母数字的组合  Made in China
    public var isAlphanumeric: Bool {
        return !base.isEmpty && base.range(of: "[^a-zA-Z0-9]", options: .regularExpression) == nil
    }
     
    
    /// 是否包含表情
    public var isIncludesEmoji:Bool{
        for i in 0...base.count {
            let c: unichar = (base as NSString).character(at: i)
            if (0xD800 <= c && c <= 0xDBFF) || (0xDC00 <= c && c <= 0xDFFF) {
                return true
            }
        }
        return false
    }
    
    ///是否是6位数字密码
    public var isSixPassWord: Bool {
        guard !base.isEmpty else{
            return false
        }
        let passRegix = "^[a-zA-Z0-9]{6}+$"
        let passTest = NSPredicate(format: "SELF MATCHES %@", passRegix)
        return passTest.evaluate(with: base)
        
    }
    
    public var removeFirst: String {
        return String(base.dropFirst())
    }
    
    public var removeLast: String {
        return String(base.dropLast())
    }
    
}

extension JX where Base == String {
    
    /// 获取文本高度
    ///
    /// - Parameters:
    ///   - font: font
    ///   - fixedWidth: fixedWidth
    public func getHeight(font : UIFont = UIFont.systemFont(ofSize: 18), fixedWidth : CGFloat) -> CGFloat {
        
        guard base.count > 0 && fixedWidth > 0 else {
            return 0
        }
        
        let size = CGSize(width:fixedWidth, height:CGFloat.greatestFiniteMagnitude)
        let text = base as NSString
        let rect = text.boundingRect(with: size, options:.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font : font], context: nil)
        
        return rect.size.height
    }
    
    /// 获取文本宽度
    /// - Parameter font: font
    public func getWidth(font : UIFont = UIFont.systemFont(ofSize: 17)) -> CGFloat {
        
        guard base.count > 0 else {
            return 0
        }
        let size = CGSize(width:CGFloat.greatestFiniteMagnitude, height:0)
        let text = base as NSString
        let rect = text.boundingRect(with: size, options:.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font : font], context:nil)
        return rect.size.width
    }
    
}

// MARK: - 字符串截取
extension String {
    /// String使用下标截取字符串
    /// string[index] 例如："abcdefg"[3] // c
    public subscript (i:Int)-> String {
        let startIndex = self.index(self.startIndex, offsetBy: i)
        let endIndex = self.index(startIndex, offsetBy: 1)
        return String(self[startIndex..<endIndex])
    }
    /// String使用下标截取字符串
    /// string[index..<index] 例如："abcdefg"[3..<4] // d
    public subscript (r:Range<Int>) -> String {
        get {
            let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
            let endIndex = self.index(self.startIndex, offsetBy: r.upperBound)
            return String(self[startIndex..<endIndex])
        }
    }
    /// String使用下标截取字符串
    /// string[index,length] 例如："abcdefg"[3,2] // de
    public subscript (index:Int , length:Int) -> String {
        get {
            let startIndex = self.index(self.startIndex, offsetBy: index)
            let endIndex = self.index(startIndex, offsetBy: length)
            return String(self[startIndex..<endIndex])
        }
    }
    // 截取 从头到i位置
    public func substring(to:Int) -> String {
        return self[0..<to]
    }
    // 截取 从i到尾部
    public func substring(from:Int) -> String {
        return self[from..<self.count]
    }
    
}


extension JX  where Base == String {
    
    
    /*
     *去掉首尾空格
     */
    public var removeHeadAndTailSpace:String {
        let whitespace = NSCharacterSet.whitespaces
        return base.trimmingCharacters(in: whitespace)
    }
    /*
     *去掉首尾空格 包括后面的换行 \n
     */
    public var removeHeadAndTailSpacePro:String {
        let whitespace = NSCharacterSet.whitespacesAndNewlines
        return base.trimmingCharacters(in: whitespace)
    }
    /*
     *去掉所有空格
     */
    public var removeAllSapce: String {
        return base.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
    }
    /*
     *去掉首尾空格 后 指定开头空格数
     */
    public func beginSpaceNum(num: Int) -> String {
        var beginSpace = ""
        for _ in 0..<num {
            beginSpace += " "
        }
        return beginSpace + self.removeHeadAndTailSpacePro
    }
    
    
    /// 替换字符串
    /// - Parameters:
    ///   - replace: 需要替换的字符串
    ///   - target: 替换为目标字符串
    /// - Returns: 返回处理过的字符串
    public func replaceString(of replace: String, with target: String) -> String{
        return base.replacingOccurrences(of: replace, with: target, options: .literal, range: nil)
    }
    
}
